package com.hotel.project.common.util;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * TODO
 *
 * @author: peng.ni
 * @date: 2022/04/13
 */
public class CopyUtils {

    public static Object copy(Object source, Object target) {
        Field[] sources = source.getClass().getDeclaredFields();
        Field[] targets = target.getClass().getDeclaredFields();

        Map<String, Object> fieldNames = new HashMap<>();
        for (Field field : sources) {
            field.setAccessible(true);
            try {
                //得到属性值
                Object fieldValue = field.get(source);
                // 得到属性名
                String fieldName = field.getName();
                if (fieldValue != null) {
                    fieldNames.put(fieldName, fieldValue);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if (!fieldNames.isEmpty()) {
            for (String fieldName : fieldNames.keySet()) {
                for (Field field : targets) {
                    field.setAccessible(true);
                    try {
                        // 得到属性名
                        String ff = field.getName();
                        if (fieldName.equals(ff)) {
                            field.set(target, fieldNames.get(fieldName));
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return target;
    }
}
